<script>
import baseForm from '@admin/packages/table-operate/src/baseForm.vue';
import { getFormDataFromId } from '@admin/api/common.js';
import { getRoute, getUrlParam, isFunction, windowClose } from '@admin/utils/index';
import { getPRoute } from '@admin/utils/route';
import { useTabStore } from '@/store/modules/tab';
import banner from './mixins/banner';
import main from './mixins/main';
export default {
  name: 'Tem1140',
  components: {
  },
  extends: baseForm,
  mixins: [main, banner],
  data() {
    return {
      isPageForm: true
    };
  },
  setup() {
    const tabStore = useTabStore();
    return {
      tabStore
    };
  },
  computed: {
    btn() {
      return {
        code: window.$CD.pageId
      };
    },
    formToolbarBtns() {
      // 工具栏按钮来源：1.页面配置工具栏 2.表单配置工具栏
      const pageToolbarBtns = this.btns.filter(btn => ['10'].includes(btn.disType));
      const formToolbarBtns = this.customFormBtns.filter(i => ['120'].includes(i.disType));
      return [...pageToolbarBtns, ...formToolbarBtns];
    },
    formParam() {
      // 自定义业务id，不从url上获取
      if (this.id) {
        return {
          id: this.id
        };
      }
      const query = JSON.parse(JSON.stringify(this.$route.query || {}));
      if (query.parentDataId && !query.id) {
        query.id = query.parentDataId;
        delete query.parentDataId;
      }
      return query;
    },
    isDetail() {
      return Boolean(this.formSetting.readonly) || this.resData.readonly == 1;
    },
    formId() {
      return this.formSetting.formId;
    },
    actionbarFixed() {
      return this.formConfig.actionbarFixed || false;
    },
    parentCode() {
      return this.formConfig.pCode || this.pCode || '';
    }
  },
  created() {},
  mounted() {
    this.initForm(this.formParam);
  },
  methods: {
    reloadForm() {
      const params = JSON.parse(JSON.stringify(this.formParam));
      if (this.saveCount && !params.id) {
        params.id = this.resData.data.id;
      }
      this.initForm(params);
    },
    // 新建表单
    createForm() {
      const params = JSON.parse(JSON.stringify(this.formParam));
      delete params.id;
      this.initForm(params).finally(() => {
        setTimeout(() => {
          this.saveCount = 0;
        });
      });
    },
    // 请求接口初始化
    initForm(extendParam = {}) {
      let param = {
        pageId: window.$CD.pageId,
        formId: this.formId
      };
      param = Object.assign(param, extendParam);
      this.formLoaded = false;
      // 请求接口前回调
      const pageId = window.$CD.pageId;
      if (
        window.$CD &&
        window.$CD.callback &&
        window.$CD.callback[pageId] &&
        window.$CD.callback[pageId].beforeRequestForm
      ) {
        window.$CD.callback[pageId].beforeRequestForm({ param });
      }
      const saveCount = this.saveCount;
      return getFormDataFromId(param)
        .then(res => {
          this.openFormDialog(res, this.btn);
        })
        .finally(() => {
          // 保留原saveCount,刷新表单时不更新
          this.saveCount = saveCount;
        });
    },
    toLastView(visitedViews, view) {
      const latestView = visitedViews.slice(-1)[0];
      if (latestView) {
        this.$router.push(latestView.fullPath);
      } else if (view.name === 'Dashboard') {
        this.$router.replace({ path: `/redirect${view.fullPath}` });
      } else {
        this.$router.push('/');
      }
    },
    redirectNav(code, query = {}) {
      const route = getRoute(code);
      this.$router.push({
        path: route.routePath,
        query
      });
    },
    async handleClose(type = 'close') {
      await this.tabStore.removeTabOnly(this.tabStore.activeTabId);
      const done = () => {
        const pRoute = getPRoute(this.code)
        if (this.parentCode) {
          this.redirectNav(this.parentCode)
        } else if (Object.keys(pRoute).length) {
          this.$router.push({
            path: pRoute.path,
            query: pRoute.query
          })
        }
      };
      if (type === 'close' && window.$CD && isFunction(window.$CD[this.formConfig.formBeforeCloseFunc])) {
        window.$CD[this.formConfig.formBeforeCloseFunc]({ done, instance: this });
      } else {
        done();
      }
    },
    // 暂存-只保存数据
    saveFormData() {
      return this.formZanSave();
    },
    // 暂存
    handleSave() {
      this.handleSaveForm({
        dialog: false,
        params: {
          pageId: window.$CD.pageId,
          formId: this.formId
        },
        submit: false
      });
    },
    // 提交
    handleSubmit(options) {
      const fullOptions = {
        done: this.handleClose,
        dialog: false,
        params: {
          pageId: window.$CD.pageId,
          formId: this.formId
        },
        ...options
      };
      this.handleConfirm(fullOptions);
    }
  }
};
</script>

<template>
  <div v-if="formLoaded">
    <page-banner v-if="showBanner && bannerPosition === 'top'" ref="pageBanner" :banner-setting="bannerSetting" />
    <ComplexForm2
      v-if="layout"
      ref="complexForm"
      class="complex-form"
      :class="[
        {
          'is-fixed': actionbarFixed
        }
      ]"
      :res-data="resData"
      :layout="layout"
      :fields="fields"
      :data="form"
      :btn="btn"
      :disabled="isDetail"
      :field-rule="fieldRule"
      :complex-config="formConfig"
      :p-instance="this"
    />
    <page-banner v-if="showBanner && bannerPosition === 'bottom'" ref="pageBanner" :banner-setting="bannerSetting" />
    <div
      class="btn-container actionbar"
      :class="[
        {
          'is-fixed': actionbarFixed
        }
      ]"
    >
      <ElButton v-if="!isDetail" size="small" @click="handleClose('back')">{{ backText }}</ElButton>
      <ElButton v-if="!isDetail && showSave" type="primary" size="small" @click="handleSave">{{ saveText }}</ElButton>
      <ElButton v-if="!isDetail && showSubmit" type="primary" size="small" @click="handleSubmit">
        {{ submitText }}
      </ElButton>
      <TableOperate
        :btns="formToolbarBtns"
        is_formpage
        class="form-operate"
        style="display: inline-block"
        size="small"
      />
      <ElButton v-if="isDetail" @click="handleClose('close')">{{ closeText }}</ElButton>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.btn-container {
  text-align: center;
  margin-top: 8px;
  .form-operate {
    margin-left: 16px;
  }
}
.complex-form {
  &.is-fixed {
    margin-bottom: 80px;
  }
}
.custom-from {
  &.is-fixed {
    margin-bottom: 80px;
  }
}
.actionbar {
  .el-button + .el-button {
    margin-left: 16px;
  }
  ::v-deep .table-operate-container {
    .btn-wraper {
      margin-right: 16px;
    }
  }
  &.is-fixed {
    position: fixed;
    bottom: 0;
    width: calc(100% - var(--g-sidebar-actual-width));
    transform: translateX(-20px);
    padding: 20px;
    z-index: 4;
    background-color: #fff;
    box-shadow:
      0 2px 4px rgba(0, 0, 0, 0.12),
      0 0 6px rgba(0, 0, 0, 0.04);
    ::v-deep .table-operate-container {
      margin-bottom: 0;
    }
  }
}
</style>

<style lang="scss" scoped>
html.screen-small {
  .complex-form.is-fixed {
    margin-bottom: 70px;
  }
  .actionbar.is-fixed {
    padding: 10px 0;
    ::v-deep .table-operate-container {
      margin-bottom: 0;
    }
  }
}
html.screen-mini {
  .complex-form.is-fixed {
    margin-bottom: 60px;
  }
  .actionbar.is-fixed {
    padding: 5px 0;
    ::v-deep .table-operate-container {
      margin-bottom: 0;
    }
  }
}
</style>
